package com.example.ruiji.common;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    private static RedisTemplate<String, String> redisTemplate;

    final static Integer defaultTTL = 30;
    final static TimeUnit defaltTimeUnit = TimeUnit.MINUTES;

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisUtil.redisTemplate = redisTemplate;
    }

    public static  <T> void setObject(String key, T value) {
        redisTemplate.opsForValue().set(key, JSON.toJSONString(value), defaultTTL, defaltTimeUnit);
    }

    public static <T> void setObject(String key, T value, final Integer TTL, final TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, JSON.toJSONString(value), TTL, timeUnit);
    }

    public static <T> T getObject(String key, Class<T> clazz) {
        String jsonString = redisTemplate.opsForValue().get(key);
        return JSON.parseObject(jsonString, clazz);
    }

    public static boolean deleteObject(String key) {
        return redisTemplate.delete(key);
    }

}

